package com.gexiaobao.pigeon.ui.auction

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.initFooter
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityThematicListBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.adapter.AdapterThematicList
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.AuctionViewModel
import com.google.gson.Gson
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kingja.loadsir.core.LoadService
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * @Author      : hxw
 * @Date        : 2024/11/12 15:05
 * @Describe    : 专题列表
 */
class ActivityThematicList : BaseActivity<AuctionViewModel, ActivityThematicListBinding>() {

    private var phoneNum: String = ""
    private lateinit var loadsir: LoadService<Any>
    private val adapter: AdapterThematicList by lazy { AdapterThematicList(arrayListOf()) }
    private var mAuctionId = ""
    private var isFollow = false

    @SuppressLint("NotifyDataSetChanged")
    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.toolBarLayout.setBackgroundColor(getColor(R.color.color_99CCFF))

        mDatabind.includeBar.tvTitle.text = "专题列表"
        mDatabind.tvThematicDetail.paint.flags = Paint.UNDERLINE_TEXT_FLAG//设置下划线
        mDatabind.tvThematicDetailPhone.paint.flags = Paint.UNDERLINE_TEXT_FLAG//设置下划线

        mAuctionId = intent.getStringExtra("auctionId").toString()
        //状态页配置
        loadsir = loadServiceInit(mDatabind.includeList.swipeRecyclerView) {
            //点击重试时触发的操作
            onRefresh(isRefresh = true)
        }

        onRefresh(isRefresh = true)

        mDatabind.includeList.swipeRecyclerView.init(LinearLayoutManager(this), adapter).let {
            it.addItemDecoration(SpaceItemDecoration(0, Util.dp2px(this, 8f)))
            it.initFooter {
                onRefresh(isRefresh = false)
            }
        }

        mDatabind.includeList.swipeRefreshLayout.init {
            onRefresh(isRefresh = true)
        }

        adapter.setOnItemClickListener { _, _, position ->
            startActivity<ActivityAuctionPigeonDetail>("goodId" to adapter.data[position].goodId, "type" to 2)
        }
    }

    private fun onRefresh(isRefresh: Boolean) {
        if (isRefresh) {
            loadsir.showLoading()
            mViewModel.getAppAuctionListTitle(mAuctionId)
        }
        mViewModel.getAppAuctionList(isRefresh, mAuctionId)
    }


    override fun createObserver() {
        super.createObserver()
        /** 关注商品或者拍卖会 */
        mViewModel.followOperationResult.observe(this) {
            mViewModel.getAppAuctionListTitle(mAuctionId)
        }
        /** 获取app专题列表 */
        mViewModel.appAuctionListResultTitle.observe(this) {
            mDatabind.data = it
            phoneNum = it.phoneNo
            if (phoneNum.isNotEmpty() && phoneNum.length >= 11) {
                val result1 = phoneNum.substring(0, 3)
                val result2 = phoneNum.substring(7, phoneNum.length)
                mDatabind.tvThematicDetailPhone.text = "$result1****$result2"
            }
            isFollow = it.isFollow
            mDatabind.tvThematicOrgType.text = when (it.orgType) {
                2 -> "协会"
                1 -> "俱乐部"
                else -> "公棚"
            }
            setFollowStatus(isFollow)
        }
        mViewModel.appAuctionListResult.observe(this) {
            loadListData(it, adapter, loadsir, mDatabind.includeList.swipeRecyclerView, mDatabind.includeList.swipeRefreshLayout)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.ivBack, mDatabind.tvThematicDetail, mDatabind.tvThematicDetailPhone, mDatabind.tvThematicFollow) {
            when (it) {
                mDatabind.tvThematicFollow -> followToAuction()
                mDatabind.tvThematicDetailPhone -> callOrg()
                mDatabind.tvThematicDetail -> startActivity<ActivityThematicDetail>("auctionId" to mAuctionId)
                mDatabind.includeBar.ivBack -> finish()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun callOrg() {
        if (phoneNum.isEmpty()) {
            RxToast.showToast("电话为空")
            return
        }
        val dialog = RxDialogDefault(this)
        dialog.setTitle("确定向以下手机号拨打电话？")
        dialog.setContent(mDatabind.tvThematicDetailPhone.text.toString())
        dialog.setSureListener {
            requestPermission(phoneNum)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun requestPermission(phoneNum: String) {
        XXPermissions.with(this)
            .permission(Permission.CALL_PHONE)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(Intent.ACTION_CALL)
                    val data = Uri.parse("tel:$phoneNum")
                    intent.setData(data)
                    startActivity(intent)
                } else {
                    RxToast.showToast("权限不足，请手动开启权限后重试")
                }
            }
    }

    private fun setFollowStatus(isFollow: Boolean) {
        if (isFollow) {
            mDatabind.tvThematicFollow.text = getString(R.string.followed)
            mDatabind.tvThematicFollow.background = ContextCompat.getDrawable(this, R.drawable.round_btn_blue5_bg)
            mDatabind.tvThematicFollow.setTextColor(Color.parseColor("#3fb5ff"))
        } else {
            mDatabind.tvThematicFollow.text = getString(R.string.follow)
            mDatabind.tvThematicFollow.background = ContextCompat.getDrawable(this, R.drawable.round_btn_5a5a5a_5radiu_bg)
            mDatabind.tvThematicFollow.setTextColor(ContextCompat.getColor(this, R.color.color_f65a5a))
        }
    }

    private fun followToAuction() {
        val followOperation = if (isFollow) 2 else 1
        val map = mapOf("auctionId" to mAuctionId.toInt(), "followOperation" to followOperation)
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        mViewModel.followOperation(body)
    }
}